package syscontrollers

import (
	"github.com/astaxie/beego/orm"
	"myadmin/sys/cache/cacheinit"
	"myadmin/sys/cache/mapstore"
	"myadmin/sys/session"
	"myadmin/sys/syscontrollers/syscommon"
	"myadmin/sys/sysmodels"
	"myadmin/sys/tool"
	"strings"
)

type User struct {
	syscommon.BaseController
}

func (c *User) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("Get", c.Get)

}

// @Title 修改用户信息
// @Description 修改用户信息
// @Success 200 {json} 创建成功
// @Failure 500 {json} 创建失败
// @router /info [post]
func(c *User) Post(){
	var err error
	user_ := c.Ctx.Input.GetData("BaseUser")
	user,ok:= user_.(sysmodels.SysUser)
	m := c.Input()
	keys := make([]string, 0, len(m))
	for k := range m {
		if k=="id"{
			continue
		}
		keys = append(keys, k)
	}
	err = c.ParseForm(&user)
	if err!=nil{
		c.JsonRep500x("上传数据失败",err)
		return
	}
	err = user.Update(keys)
	if err!=nil{
		c.JsonRep500x("更新失败",err)
		return
	}
	//跟新成功 更新session
	sel_ := c.Ctx.Input.GetData("Session")
	sel,ok:=sel_.(*session.Session)
	if !ok{
		c.JsonRep500("更新session失败")
		return
	}
	sel.User = user
	authtoken := c.Ctx.Input.Header("Authorization")
	session.Ses.Update(authtoken,sel)
	c.JsonRep200x("更新成功",user)

}


// @Title 获取用户信息
// @Description 获取用户信息
// @Success 200 {json} 创建成功
// @Failure 500 {json} 创建失败
// @router /info [get]
func(c *User) Get(){
	roleauth:=mapstore.Get("roleAuths")
	if roleauth == nil{
		roleauth = cacheinit.SetRoleAuth()
	}
	user_ := c.Ctx.Input.GetData("BaseUser")
	user := user_.(sysmodels.SysUser)
	err:=user.GetById()
	if err== orm.ErrNoRows{
		c.JsonRep500("账号失效请重新登录")
		return
	}

	m:=tool.Obj2Map(user)
	roleauths:=roleauth.(map[string][]string)
	m["authorities"] = roleauths[m["RoleName"].(string)]

	tmp:=map[string]interface{}{}
	for k,v:=range m{
		tmp[strings.ToLower(k)] = v
	}
	c.JsonRep200x("获取成功",tmp)
}

